<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Address;
use App\Models\AddressSnapshot;
use App\Models\MallOrder;
use App\Models\Order;
use Illuminate\Http\Request;

class AddressController extends BaseController
{
    public $model = Address::class;


    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $user_id = $this->getUserId();
        $users = Address::where('user_id', $user_id)->orderBy("is_default", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($users);
    }


    public function store(Request $request) {
        $input = $request->input();
        $input['detail'] = $input['detail'] ?? '';
        $input['user_id'] = $this->getUserId();
        $id = \request("id");
        $exists = Address::where('user_id', $input['user_id'])->exists();
        if (!$exists)
            $input['is_default'] = 1;

        $is_default = $request->input('is_default', 0);
        if ($is_default) {
            $this->model::where('user_id', $input['user_id'])->update(['is_default' => 0]);
        }

        if ($id) {
            $one = $this->model::find($id);
            if (!$one) {
                return $this->failed('ID不存在');
            }
            $one->update($input);
        } else {
            $info = $this->model::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function info(Request $request) {
        $is_default = $request->input('is_default', 0);
        $id = $request->input('id');
        $info = Address::when($is_default, function ($q) use($is_default){
            $q->where('is_default', $is_default);
        })->when($id, function ($q) use($id){
            $q->where('id', $id);
        })->where('user_id', $this->getUserId())->first();
        return $this->success($info);
    }

    public function updateOrderAddress(Request $request) {
        $this->validate($request, [
            'order_id' => 'required',
            'address_id' => 'required',
        ]);
        $input = $request->input();
        $input['user_id'] = $this->getUserId();
        $id = \request("order_id");
        $order = MallOrder::find($id);
        if (!$order)
            return $this->failed('订单号不存在');

        if (!in_array($order->status, [MallOrder::STATUS_WAIT_PRODUCT, MallOrder::STATUS_WAIT_PAY]))
            return $this->failed('已发货，不允许修改');

        if ($order->is_start_send)
            return $this->failed('已存在部分发货商品，不允许修改');

        $address = Address::find($input['address_id']);
        if (!$address)
            return $this->failed('地址不存在');

        $arr_address = $address->toArray();
        unset($arr_address['id'], $arr_address['address_display']);
        $address_snapshot = AddressSnapshot::find($order->address_snapshot_id);
        foreach ($arr_address as $key => $value) {
            $address_snapshot-> {$key} = $value;
        }
        $address_snapshot->save();
        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'id' => 'required'
        ]);
        $id = $request->input('id');
        $address = Address::find ($id);
        $user_id = $this->getUserId();
        if (!$address)
            return $this->failed('地址不存在');
        if ($address->user_id != $user_id)
            return $this->failed('无权删除别人地址');

        $is_default = $address->is_default;

        if ($address->delete()) {
            if ($is_default) {
                $latest = Address::where('user_id', $user_id)->orderBy('id', 'desc')->first();
                if ($latest) {
                    $latest->is_default = 1;
                    $latest->save();
                }
            }
        }
        return $this->success([]);
    }

}

